package com.playball.lottery.nt.orjdd;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;





import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.playball.lottery.util.AppUtils;

import static com.playball.lottery.util.AppUtils.convertStreamToString;

public class GetScoreJsonData {

	private static int connectTimeout = 30 * 1000;
	private static int readTimeout = 30 * 1000;
	// 比分地址。单独
	private static final String urlPath = "http://live.jiangduoduo.com/ajax/LiveScoreHandler.ashx?";
	public static Proxy mProxy = null;
	public static Context mContext;

	public static String getInputStreamByPost(Map<String, Object> params, Context context) throws Exception {
		mContext = context;

		// 拼接参数
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, Object> entry : params.entrySet()) {
			sb.append(entry.getKey()).append("=").append(entry.getValue().toString());
			sb.append("&");
		}
		String data = sb.deleteCharAt(sb.length() - 1).toString();
		// 检查网络
		detectProxy();
		// 发送请求
		HttpURLConnection conn = null;
		String strResponse = null;
		try {
			URL url = new URL(urlPath);
//			System.out.println(urlPath+data);
			// 打开连接
			if (mProxy != null) {
				conn = (HttpURLConnection) url.openConnection(mProxy);
			} else {
				conn = (HttpURLConnection) url.openConnection();
			}
			// 设置提交方式
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			// post方式不能使用缓存
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(true);
			byte[] requestStringBytes = data.getBytes("UTF-8");
			// 设置连接超时时间
			conn.setConnectTimeout(connectTimeout);
			conn.setReadTimeout(readTimeout);
			// 配置本次连接的Content-Type，配置为application/x-www-form-urlencoded
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			// 维持长连接
			conn.setRequestProperty("Connection", "Keep-Alive");
			// 设置浏览器编码
			conn.setRequestProperty("Charset", "UTF-8");
			// 开始连接
			conn.connect();

			OutputStream dos = conn.getOutputStream();
			// 将请求参数数据向服务器端发送
			dos.write(requestStringBytes);
			dos.flush();

			if (conn.getResponseCode() == 200) {
				// 获得服务器端输出流
				InputStream content = conn.getInputStream();
				strResponse = AppUtils.convertStreamToString(content);
//				System.out.println("response " + strResponse);
				mProxy = null;
				return strResponse;
			}
		} catch (IOException e) {
//			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		return null;
	}

	// 通过输入流获得字节数组
	public static byte[] readStream(InputStream is) throws Exception {
		byte[] buffer = new byte[1024];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int len = 0;
		while ((len = is.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		is.close();
		return bos.toByteArray();
	}

	/**
	 * 获取网址内容
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String getContent(String url) throws Exception {
		StringBuilder sb = new StringBuilder();

		HttpClient client = new DefaultHttpClient();
		HttpParams httpParams = client.getParams();
		// 设置网络超时参数
		HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
		HttpConnectionParams.setSoTimeout(httpParams, 5000);
		HttpResponse response = client.execute(new HttpGet(url));
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			reader.close();
		}
		return sb.toString();
	}

	/**
	 * 检查代理，是否cnwap接入
	 */
	private static void detectProxy() {
		ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni != null && ni.isAvailable() && ni.getType() == ConnectivityManager.TYPE_MOBILE) {
			String proxyHost = android.net.Proxy.getDefaultHost();
			int port = android.net.Proxy.getDefaultPort();
			if (proxyHost != null) {
				final InetSocketAddress sa = new InetSocketAddress(proxyHost, port);
				mProxy = new Proxy(Proxy.Type.HTTP, sa);
			}
		}
	}
}
